class PurchaseOrdersController < ApplicationController
  before_action :set_purchase_order, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    @purchase_orders = PurchaseOrder.where(build_search(search_params)).order(created_at: :desc).page(params[:page])
    
    respond_to do |format|
      format.html{}      
      format.json {render json:@purchase_orders }
    end
    
  end

  def show    
    respond_with(@purchase_order)    
  end

  def new
    @purchase_order = PurchaseOrder.new
    respond_with(@purchase_order)
  end

  def edit
  end

  def create
    @purchase_order = PurchaseOrder.new(purchase_order_params)
    @purchase_order.init_amount_paid_balance
    @purchase_order.save
    respond_with(@purchase_order)
  end

  def update
    @purchase_order.update(purchase_order_params)
    respond_with(@purchase_order)
  end

  def destroy
    @purchase_order.destroy
    respond_with(@purchase_order)
  end

  private
    def set_purchase_order
      @purchase_order = PurchaseOrder.find(params[:id])
    end

    def purchase_order_params
      params.require(:purchase_order).permit(:po_number, :supplier_name, :date, :payment_term, :amount, :invoice_state, :invoice_no, :invoice_amount, :invoice_received_date, :amount_paid, :balance, :supplier_id)
    end
    
    def search_params     
        if params[:purchase_order].present?  
          purchase_order_params.permit(:po_number)
        end                     
    end
end
